﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;

namespace OF.Utility
{
    public static class EnumHelper
    {
        /// <summary>  
        /// 根据值得到中文备注  
        /// </summary>  
        /// <param name="e"></param>  
        /// <param name="value"></param>  
        /// <returns></returns>  
        public static String GetEnumDesc(this Type e, int? value)
        {
            FieldInfo[] fields = e.GetFields();
            for (int i = 1, count = fields.Length; i < count; i++)
            {
                if ((int)System.Enum.Parse(e, fields[i].Name) == value)
                {
                    DescriptionAttribute[] EnumAttributes = (DescriptionAttribute[])fields[i].
                GetCustomAttributes(typeof(DescriptionAttribute), false);
                    if (EnumAttributes.Length > 0)
                    {
                        return EnumAttributes[0].Description;
                    }
                }
            }
            return "";
        }

        public static string GetName<T>(string val)
        {
            return Enum.GetName(typeof(T), val);
        }

        public static string GetEnumName<T>( object val)
        {
            if (val == null || val.ToString().Length == 0 || val.ToString() == "-1")
            {
                return "未知";
            }
            try
            {
                return Enum.Parse(typeof(T), val.ToString()).ToString();
            }
            catch
            { }
            return "未知";
        }

        public static Dictionary<string, string> GetListFormEnum<T>()
        {
            return Enum.GetValues(typeof(T)).Cast<int>()
                .ToDictionary(i => Enum.GetName(typeof(T), i), i => i.ToString());
        }

    }
}
